package com.example.a2209_shop.fg

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2209_shop.R
import com.example.a2209_shop.adapter.ShopAdapter
import com.example.a2209_shop.database.CarSearchEntity
import com.example.a2209_shop.database.DBUtils
import com.example.a2209_shop.databinding.ActivityCarSearchBinding
import com.example.a2209_shop.fgViewModel.CarViewModel
import com.example.base.mvvm.BaseActivity

@Route(path = "/app/CarSearchActivity")
class CarSearchActivity : BaseActivity<ActivityCarSearchBinding,CarViewModel>() {
    lateinit var shopAdapter: ShopAdapter
    override fun initData() {
        viewModel.searchSuccess.observe(this){
            shopAdapter.data.clear()
            shopAdapter.data.addAll(it)
            shopAdapter.notifyDataSetChanged()
            if(it.size==0){
                ToastUtils.showLong("未查询到相关数据")
            }
        }
    }

    override fun initView() {
        shopAdapter = ShopAdapter()
        binding.carRv.adapter = shopAdapter
        binding.carRv.layoutManager =StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)

        binding.carSearch.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if(query!=null){
                   viewModel.search(query)
                    //保存记录，新增到数据库中
                    val carSearchEntity = CarSearchEntity(query,SPUtils.getInstance().getInt("id"))
                    DBUtils.getDb().getCarSearchDao().insert(carSearchEntity)
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return false
            }
        })
        //查询数据库中的数据
        val query = DBUtils.getDb().getCarSearchDao().query(SPUtils.getInstance().getInt("id"))
        if (query != null) {
            if(query.isNotEmpty()){
                binding.carCg.removeAllViews()
                query.forEach {
                    val key = it.key
                    val view = LayoutInflater.from(this).inflate(R.layout.item_car_chip,null)
                    view.findViewById<TextView>(R.id.car_key).text = key
                    binding.carCg.addView(view)

                    view.setOnClickListener {
                        binding.carSearch.setQuery(key,true)
                    }
                }
            }
        }
    }

    override fun getViewModel() = CarViewModel::class.java

    override fun getLayout() = R.layout.activity_car_search

}